<script setup name="fieldConfig">
import { GetMenuPageAPI } from "@/api/system/printConfig";
import { ConfigFieidAPI, GetDetailsAPI } from "@/api/system/printConfig.js";
const assist = ref(true);
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
//  树结构 页面数据
const menuPage = ref([]);
const inputRef = ref(null);
const open = ref(true);
const intro1 = ref(null);
const intro2 = ref(null);
const intro3 = ref(null);
const intro4 = ref(null);
const intro5 = ref(null);
const intro6 = ref(null);

// 获取列表
const getMenuPage = async () => {
  try {
    const res = await GetMenuPageAPI();
    menuPage.value = res.data;
  } catch (error) {
    console.log(error);
  } finally {
  }
};

getMenuPage();

// 页面位置
const menuPageValue = ref();

// 加载状态
const loading = ref(false);

// 列表数据
const tableData = ref([{}]);

// 下拉状态
const selList = ref([
  {
    label: "普通文本",
    value: "text",
  },
  {
    label: "二维码",
    value: "qrcode",
  },
  {
    label: "条形码",
    value: "barcode",
  },

  {
    label: "图片",
    value: "image",
  },
]);

// 加载状态
const btnLoading = ref(false);
const tabSel = ref([]);
const handleSelectionChange = (row) => {
  tabSel.value = row;
};

//  弹窗
const getDailt = async () => {
  try {
    proxy.$modal.loading("请稍候...");
    loading.value = true;
    const { data: res } = await GetDetailsAPI(menuPageValue.value);
    tableData.value = res.map((item) => ({
      printName: item.printName,
      printField: item.printField,
      printType: item.printType,
      data: item.data,
    }));
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
    proxy.$modal.closeLoading();
  }
};

// 保存
const submit = async () => {
  if (!menuPageValue.value) return proxy.warningMsg("请选择要配置的页面位置！");

  const isif = tableData.value.every(
    (item) => (item.printName && item.printField) || item.printType == "image"
  );
  if (!isif) return proxy.warningMsg("字段名称和字段变量都必填");
  await tableData.value.forEach((item) => {
    item.printId = route.query.id;
    // item.printCorrelation = menuPageValue.value[menuPageValue.value.length - 1]

    if (item.printType == "text") {
      item.icon = "wenben";
      item.printType = "text";
    }
    if (item.printType == "qrcode") {
      item.icon = "erweima";
      item.textType = "qrcode";
      item.printType = "qrcode";
    }
    if (item.printType == "barcode") {
      item.icon = "tiaoxingma";
      item.textType = "barcode";
      item.printType = "barcode";
    }
    if (item.printType == "image") {
      item.icon = "tupian";
      item.textType = "image";
      item.printType = "image";
    }
  });
  try {
    proxy.$modal.loading("请稍候...");
    btnLoading.value = true;
    await ConfigFieidAPI({
      menuId: menuPageValue.value,
      dispositionList: tableData.value,
    });
    proxy.successMsg("操作OKK");
    tableData.value = [];
    getDailt();
  } catch (err) {
    console.log(err);
  } finally {
    btnLoading.value = false;
    proxy.$modal.closeLoading();
  }
};

// 重置
const reset = (scope) => {
  tableData.value.splice(scope.$index, 1, {
    printName: "",
    printField: "",
    printType: "text",
  });
};

// 添加、当前下的添加
const add = (scope) => {
  if (scope) {
    tableData.value.splice(scope.$index + 1, 0, {
      printName: "",
      printField: "",
      printType: "text",
      data: "",
    });
  } else {
    tableData.value.push({
      printName: "",
      printField: "",
      printType: "text",
      data: "",
    });
  }
};

// 删除
const remove = (scope) => {
  if (tabSel.value.length > 0) {
    tabSel.value.forEach((item) => {
      const Find = tableData.value.findIndex(
        (itemy) =>
          item.printType == itemy.printType &&
          item.printField == itemy.printField
      );
      tableData.value.splice(Find, 1);
    });
  } else {
    tableData.value.splice(scope.$index, 1);
  }
};

const change = (val, c) => {
  // 校验字段变量不能是纯数字！
  if (/^\d+$/.test(val.row.printField)) {
    proxy.warningMsg("字段变量不能是纯数字！");
    tableData.value[val.$index].printField = "";
    return;
  }

  // 校验字段变量不能有特殊符号！
  if (/[.*+?^${}()|[]]/g.test(val.row.printField)) {
    proxy.warningMsg("字段变量不能有特殊符号！");
    tableData.value[val.$index].printField = "";
    return;
  }
};

// 动态校验
let i = -1;
let validator = (rule, value, callback) => {
  i++;
  if (i >= tableData.value.length) return (i = 0);
  if (!tableData.value[i]) return;

  if (!value && tableData.value[i].printType != "image")
    return callback(new Error("请填写字段变量"));
  callback();
};

// 列表枚举
const column = ref([
  { label: "字段名称", prop: "printName", showText: false, required: true },
  {
    label: "字段变量",
    prop: "printField",
    showText: false,
    required: true,
    rules: [{ validator: validator, trigger: "blur" }],
  },
  { label: "类型", prop: "printType", showText: false, required: true },
  { label: "默认数据", prop: "data", showText: false },
  { label: "操作", prop: "x" },
]);

// 引导
onMounted(() => {
  menuPageValue.value = route.query.printPageId;
  getDailt();
  // proxy
  //   .intro()
  //   .setOptions({
  //     steps: [
  //       {
  //         element: document.querySelector(".intro1"),
  //         intro: "点击拉下，选择一个页面",
  //         position: "right",
  //       },
  //       {
  //         element: document.querySelector(".intro2"),
  //         intro: "点击添加一条数据吧",
  //         position: "left",
  //       },

  //       {
  //         element: document.querySelector(
  //           ".el-table_1_column_2 el-table__cell"
  //         ),
  //         title: "第三步",
  //         intro: "填写打印表头",
  //         position: "bottom",
  //       },
  //       {
  //         element: document.querySelector(
  //           ".el-table_1_column_3 el-table__cell"
  //         ),
  //         intro: "Tooltip has position top",
  //         position: "top",
  //       },
  //     ],
  //   })
  //   .start();
});
</script>

<template>
  <div class="app-container">
    <el-tour v-model="open">
      <el-tour-step
        :target="intro1?.$el"
        title="第一步"
        description="点击拉下，选择一个页面"
      >
      </el-tour-step>
      <el-tour-step
        :target="intro2?.$el"
        title="第二步"
        description="点击添加一条数据吧"
      />
      <el-tour-step
        :target="intro3?.$el"
        title="第三步"
        description="填写打印表头"
      />
      <el-tour-step
        :target="intro4?.$el"
        title="第四步"
        description="填写打印字段变量"
      />
      <el-tour-step
        :target="intro5?.$el"
        title="第五步"
        description="选择不同的类型"
      />
      <el-tour-step
        :target="intro6?.$el"
        title="第六步"
        description="请填写默认数据吧（二维码和条形码没有默认数据会导致看不见哦）"
      />
    </el-tour>
    <div class="flex-between">
      <div class="intro1">
        <el-tree-select
          ref="intro1"
          v-model="menuPageValue"
          :data="menuPage"
          default-expand-all
          node-key="id"
          :props="{
            label: 'menuName',
            value: 'menuId',
            children: 'children',
          }"
          @change="getDailt(menuPageValue)"
        />
      </div>
      <div>
        <el-button type="warning" @click="router.push('/system/printTemplate')"
          >关闭此页面</el-button
        >
        <el-popover
          placement="top-start"
          title="提示"
          :width="400"
          trigger="hover"
          content="根据左侧页面位置，查询字段内容。如没有字段需选择页面位置，添加字段点击保存。"
        >
          <template #reference>
            <el-button @click="assist = true">帮助</el-button>
          </template>
        </el-popover>

        <el-button ref="intro2" @click="add(false)">添加一条</el-button>
        <el-button @click="submit">保存</el-button>
      </div>
    </div>

    <!-- <xiaoheTable :tableData="tab" :data="tableData" /> -->
    <!-- <TransitionGroup name="fade" tag="tbody" class="container"> -->

    <p-table
      keyId="printField"
      calss="tableClass"
      :isSel="false"
      :loading="loading"
      :column="column"
      :data="tableData"
      className="tableClass"
      @change="handleSelectionChange"
    >
      <template #columnCell="{ column, record, scope }">
        <el-input
          ref="intro3"
          v-if="column.prop == 'printName'"
          v-model="record.printName"
        />

        <div v-if="column.prop == 'printField'">
          <!-- v-if="record.printType != 'image'" -->
          <el-input
            ref="intro4"
            id="inputbox"
            v-model="record.printField"
            @change="change(scope, column)"
            :disabled="record.printType == 'image'"
          />
        </div>

        <p-select
          data-step="5"
          ref="intro5"
          v-if="column.prop == 'printType'"
          v-model="record.printType"
          :option="selList"
        />
        <div v-if="column.prop == 'data'">
          <p-imageUpload
            :limit="1"
            v-if="record.printType == 'image'"
            v-model="record.data"
            :option="selList"
          />
          <el-input ref="intro6" v-else v-model="record.data" />
        </div>
        <div v-if="column.prop == 'x'">
          <el-link type="primary" text="重置" @click="reset(scope)" />
          <el-link type="primary" text="删除" @click="remove(scope)" />
          <el-link type="primary" text="添加" @click="add(scope)" />
        </div>
      </template>
    </p-table>
    <!-- </TransitionGroup> -->

    <!-- <p-dialog v-model="assist" title="提示" @close="assist = false" width="60%">
      <template #body>
        <img
          style="width: 100%; height: 100%"
          src="@/assets/images/12.png"
          alt=""
        />
      </template>
    </p-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
.container {
  position: relative;
  padding: 0;
  width: 100%;
}

/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: scaleY(0.01) translate(30px, 0);
}

/* 3. 确保离开的项目被移除出了布局流
      以便正确地计算移动时的动画效果。 */
.fade-leave-active {
  position: absolute;
}
</style>
